#region
/* Adoor.NET - Object/Relational mapping framework leveraging ADO.NET`s powerful disconnected mode.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *  
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *  
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */ 
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Adoor.Object.Disconnected;
using Adoor.Object.Domain;
using Adoor.Object.Entity;
using Adoor.Object.Query;

namespace Adoor.Object.Relational
{
    public abstract class MultipleReferenceMapping<TReference> : IService, IReferenceMapping, IReferenceReader<TReference>, ISingleReferenceReader<TReference>
	{
		private ReferenceData referenceData;
		public MultipleReferenceMapping(ReferenceData referenceData, string sourceForeignKey, string targetForeignKey)
		{
			this.referenceData = referenceData;
			this.targetForeignKey = targetForeignKey;
			this.sourceForeignKey = sourceForeignKey;
            this.ReferenceData.RegisterService(typeof(IReferenceReader), this);
            this.ReferenceData.RegisterService(typeof(IReferenceReader<TReference>), this);
			if (this.ReferenceData.IsSingleReference)
                this.ReferenceData.RegisterService(typeof(ISingleReferenceReader<TReference>), this);
		}

		public void Initialize()
		{
			this.ReferenceData.RegisterService(typeof(IReferenceMapping), this);
		}

		public ReferenceData ReferenceData
		{
			get { return this.referenceData; }
		}

		public string SourceForeignKey
		{
			get { return this.sourceForeignKey; } 
		}

		public string TargetForeignKey
		{
			get { return this.targetForeignKey; }
		}

		public void InsertDataColumn(IList<System.Data.DataColumn> dataColumns)
		{
			//nothing
		}

		public void FetchTargetEntities(IEntity sourceEntity)
		{
			
			DataSetObjectStorage storage = (DataSetObjectStorage)sourceEntity.State.Storage;
			PreloadFlags flags = PreloadFlags.TargetEntities;
			ObjectContext context = storage.Context;
			if (context != null && !context.Disconnected && !sourceEntity.State.IsReferenceComplete(this.ReferenceData.TargetRole, ref flags)) 
			{
                ObjectPath source = this.ReferenceData.SourceData.GetPath(this.ReferenceData.SourceData.EntityType.Name).Where("[" + this.ReferenceData.SourceData.EntityType.Name + "] = ?");
				source = source.Join(false, this.ReferenceData.SourceData.EntityType.Name, this.ReferenceData.TargetRole, this.ReferenceData.TargetRole, null);
				IEntityLoader loader = (IEntityLoader)this.ReferenceData.TargetData.GetService(typeof(IEntityLoader));
				loader.Load(context, this.ReferenceData.TargetRole, source, new object[] { sourceEntity });
				sourceEntity.State.CompleteReference(this.ReferenceData.TargetRole, PreloadFlags.TargetEntities);
			}
		}

		public TReference GetValue(IEntity sourceEntity)
		{
            ICollection<TReference> c = this.Collect(sourceEntity);
            IEnumerator<TReference> enumerator = c.GetEnumerator();
			if (!enumerator.MoveNext())
                return default(TReference);
            TReference result = enumerator.Current;
			if (enumerator.MoveNext())
				throw new Exception("constraint violation: too many entities found");
			return result;
		}


		public abstract IList<TReference> Collect(IEntity sourceEntity);
        public abstract System.Collections.IEnumerator EnumTargetKeys(IEntity sourceEntity);
		public abstract void FetchReference(ObjectContext context, ObjectPath path, object args, string root, string alias, bool isGloballyLoaded);
		public abstract void InitInverseReferenceReader<TInverse>(ReferenceData inverseReferenceData);

		private string sourceForeignKey;
		private string targetForeignKey;
	}
}
